﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using XProject.GUI;
using XProject.Entity;

namespace XProject
{
    
    public partial class MainForm : Form
    {
        bool toggle=false;
        DAO.SayingDAO daoSaying = new XProject.DAO.SayingDAO();
        static Account account = new Account();
        //private int childFormNumber = 0;
        public static Account CurrentAccount
        {
            get { return account; }
            set { account = value; }
        }
        public MainForm()
        {
            InitializeComponent();
        }
        public void Slide(int maxpos,int minpos,int step, bool up)
        {
            if (up)
            {
                for (int i = minpos; i < maxpos; i += step)
                {
                    pnlToggle.Width = i;
                }
            }
            else
            {
                for (int i = maxpos; i > minpos; i -= step)
                {
                    pnlToggle.Width = i;
                }
            }
        }

        public void SetPersonalSetting()
        {
            if (MainForm.CurrentAccount!=null)
            {
                string image_path = MainForm.CurrentAccount.PersonImage;
                if (File.Exists(image_path)) picPersonImage.Image = Image.FromFile(image_path);
            }
        }

        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void CopyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard to insert the selected text or images into the clipboard
        }

        private void PasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // TODO: Use System.Windows.Forms.Clipboard.GetText() or System.Windows.Forms.GetData to retrieve information from the clipboard.
        }

       

        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void btnToggle_Click(object sender, EventArgs e)
        {         
                Slide(220,1,30,toggle);           
            toggle = !toggle;
        }

        private void pnlToggle_MouseEnter(object sender, EventArgs e)
        {
         //   Slide(200, 1, 10, true);
            
        }

        private void pnlToggle_MouseLeave(object sender, EventArgs e)
        {
           // Slide(200, 1, 10, false);         
        }

        private void MDIParent1_Load(object sender, EventArgs e)
        {
            string icon = System.Configuration.ConfigurationManager.AppSettings["icon"];
            if (System.IO.File.Exists(icon)) { this.Icon = new Icon(icon); }

            if (CurrentAccount != null)
            {
                if (CurrentAccount.AccountID > 0)
                {                    
                    mnuTool.Visible = true;
                    mnuSys_Login.Visible = false;
                    mnuSys_Logout.Visible = true;
                    if (CurrentAccount.AccountID == 1)
                    {
                        mnuRemoveAccount.Visible = true;
                        mnuRegister.Visible = true;
                    }
                    SetPersonalSetting();
                    if (CurrentAccount.Person.Name != "") lblFullName.Text = CurrentAccount.Person.Name;
                    else lblFullName.Text = MainForm.CurrentAccount.Username;
                }
            }
            lblDateOfWeek.Text = DateTime.Today.DayOfWeek.ToString();
            lblToday.Text = DateTime.Today.ToShortDateString();
            Util.LunarDate ld = new XProject.Util.LunarDate();
            ld.SetSolarDate(DateTime.Today);
            lblLunarDate.Text =ld.ToString()+" - " +"Ngày " +ld.GetDayName() +", tháng "+ld.GetMonthName()+", năm "+ld.GetYearName();
            //start timer to keep the time
            timer1.Start();
            SetPersonalSetting();
            //load saying in random
            button1_Click(sender, e);
            DAO.EventDAO daoEvent = new XProject.DAO.EventDAO();
            IList<Entity.Event> list = daoEvent.GetEventByDate(DateTime.Today);
            string st = "";
            foreach (Event ev in list)
            {
                st += "\n* "+ev.Content;
            }
            lblTodayEvent.Text = st;
            //show login
            if(CurrentAccount==null) mnuSys_Login_Click(sender,e);
            
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            lblTime.Text = DateTime.Now.ToShortTimeString();         
        }

        private void mnuPerContact_Click(object sender, EventArgs e)
        {
            if (!FormExisted("Contact"))
            {
                XProject.GUI.ContactManager frmContact = new ContactManager();
                frmContact.MdiParent = this;
                frmContact.Show();
                frmContact.WindowState = FormWindowState.Maximized;
            }
        }

        private void mnuEvent_Click(object sender, EventArgs e)
        {
            if (!FormExisted("Events"))
            {
                EventManager frmEventMng = new EventManager();
                frmEventMng.MdiParent = this;
                frmEventMng.Show();
                frmEventMng.WindowState = FormWindowState.Maximized;
            }
        }

        private void mnuDiary_Click(object sender, EventArgs e)
        {
            if (!FormExisted("My Diary"))
            {
                Form childForm = new DiaryTool();
                // Make it a child of this MDI form before showing it.
                childForm.MdiParent = this;
                childForm.Show();
                childForm.WindowState = FormWindowState.Maximized;
            }
        }
        public bool FormExisted(string title)
        {
            title=title.ToLower();
            foreach (Form form in this.MdiChildren)
            {
                if (title == form.Text.ToLower())
                {
                    form.Focus();
                    if(form.WindowState != FormWindowState.Maximized)
                    form.WindowState = FormWindowState.Maximized;
                    return true;
                }
            }
            return false;
        }

        private void mnuSys_Login_Click(object sender, EventArgs e)
        {
            Login frmLogin = new Login();
            label:
            if (frmLogin.ShowDialog() == DialogResult.Yes)
            {
                account = frmLogin.Account;
                mnuTool.Visible = true;
                //only administrator can use this menu
                if (MainForm.CurrentAccount.Role == 1)
                {
                    mnuRemoveAccount.Visible = true;                  
                    mnuRegister.Visible = true;
                }
                mnuSys_Login.Visible = false;
                mnuSys_Logout.Visible = true;
                SetPersonalSetting();
                if (CurrentAccount.Person.Name != "") lblFullName.Text = CurrentAccount.Person.Name;
                else lblFullName.Text = MainForm.CurrentAccount.Username;
                if (DateTime.Now.Month == CurrentAccount.Person.DateOfBirth.Month && DateTime.Now.Day == CurrentAccount.Person.DateOfBirth.Day)
                {
                    if (MessageBox.Show("Dong ho he thong dung khong?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes)
                    {
                        MessageBox.Show("Hoi cho chac i ma. Chuc mung sinh nhat. Happy birth day to you! ^0^");
                    }
                    else MessageBox.Show("Vay thi khong co gi ^^");
                    
                }
            }
            else if(frmLogin.DialogResult==DialogResult.No)
            {
                mnuTool.Visible = false;
                MessageBox.Show("Invalid username or password. Please try again");
                goto label;
            }
            
        }

        private void mnuSys_Logout_Click(object sender, EventArgs e)
        {
            account = null;
            mnuSys_Login.Visible = true;
            mnuSys_Logout.Visible = false;
            mnuTool.Visible = false;
            mnuRemoveAccount.Visible = false;
            mnuRegister.Visible = false;
            lblFullName.Text="User";
            picPersonImage.Image = null;
            foreach (Form form in this.MdiChildren)
            {
                form.Dispose();
            }
        }
        public void ShowEvents()
        {
            //DAO.EventDAO daoEvent = new XProject.DAO.EventDAO();
            //IList<Entity.Event> events = daoEvent.GetEventByPeriodOfTime(MainForm.CurrentAccount.AccountID, DateTime.Today, DateTime.Today.AddDays(7));

            //Font fTitle = new Font("Arial", 9, FontStyle.Bold);
            //Font fContent = new Font("Arial", 10, FontStyle.Regular);
            //foreach (Event ev in events)
            //{
            //    rtfEvents.SelectionColor = Color.Green;
            //    rtfEvents.SelectionFont = fTitle;
            //    rtfEvents.AppendText("\n" + ev.StartTime.ToShortDateString() + " - " + ev.StartTime.ToLongTimeString() + "\n");
            //    if (ev.Priority < 2) color = Color.Red;
            //    else if (ev.Priority == 2) color = Color.Blue;
            //    else color = Color.Brown;
            //    rtfEvents.SelectionColor = color;
            //    rtfEvents.SelectionFont = fContent;
            //    rtfEvents.AppendText(ev.Content + "\n");
            //}
        }

        private void btnSchedule_Click(object sender, EventArgs e)
        {
            Panel pnlSchedule = new Panel();
            Button but = new Button();
            but.Text = "x";
            but.Click += new EventHandler(but_Click);
            CheckedListBox cklSchedule = new CheckedListBox();
            pnlSchedule.Controls.Add(but);
            pnlSchedule.Controls.Add(cklSchedule);
            fpnMiniTask.Controls.Add(pnlSchedule);
        }

        void but_Click(object sender, EventArgs e)
        {
            
        }

        private void lnkChangePic_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (MainForm.CurrentAccount == null) return;
            DAO.AccountDAO daoAccount = new XProject.DAO.AccountDAO();
            OpenFileDialog dlgOpen = new OpenFileDialog();
            dlgOpen.Filter = "Image files (*.jpg, *.png, *.bmp, *.gif)|*.jpg;*.png;*.bmp;*.gif";
            if (dlgOpen.ShowDialog() == DialogResult.OK)
            {
                string filename = dlgOpen.FileName;
                System.Configuration.ConfigurationManager.AppSettings["image_path"] = filename;
                picPersonImage.Image = Image.FromFile(filename);
                MainForm.CurrentAccount.PersonImage = filename;
                daoAccount.SetImage(MainForm.CurrentAccount);
            }
        }

        private void mnuRegister_Click(object sender, EventArgs e)
        {
            GUI.Registration frmReg = new Registration();
            frmReg.ShowDialog(this);
        }

        private void mnuChangePass_Click(object sender, EventArgs e)
        {
            GUI.PasswordChange frmPassChange = new PasswordChange();
            frmPassChange.ShowDialog(this);
        }

        private void mnuRemoveAccount_Click(object sender, EventArgs e)
        {
            GUI.AccountManager frmAccountMng = new AccountManager();
            frmAccountMng.ShowDialog(this);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Collections.ArrayList keyList = daoSaying.GetAllKey();
            Random rd = new Random((int)DateTime.Now.Ticks);
            
            int index = rd.Next(keyList.Count);
            Saying saying = daoSaying.GetByID((int)keyList[index]);
            lblSayingContent.Text = saying.Content;
            lblSayingOwner.Text = saying.Owner;
            
        }

        private void mnuExit_Click(object sender, EventArgs e)
        {
            foreach (Form f in this.MdiChildren)
            {
                f.Close();
            }
            if (this.MdiChildren.Length == 0)
            {
                this.Dispose();               
            }
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GUI.About dlgAbout = new About();
            dlgAbout.ShowDialog(this);
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Dispose();
            GC.Collect();
        }

        private void mnuSaying_Click(object sender, EventArgs e)
        {
            if (!FormExisted("Saying"))
            {
                SayingManager frmSaying = new SayingManager();
                //frmSaying.MdiParent = this;
                frmSaying.Show();
            }
        }

 

    }
}
